import { useRef, useState } from "react"

export interface useInfiniteScrollOptions {
  initPage?: number //初始加载的页面，默认是1
  initPageSize?: number //每页加载数量，默认是10条
}
export type useInfiniteScrollRequest = (
  pageNo: number,
  pageSize: number
) => Promise<{ data?: any[]; total?: number }>

export type useInfiniteScrollReturn = {
  list: any[]
  hasMore: boolean
  loadMore: (isRetry: boolean) => Promise<void>
  reset: () => void
}
/**
 * 无限滚动hook,配合ant-mobile/infinite-scroll使用
 * @param request 一个异步函数，接收两个参数：pageNo,pageSize;函数内同步请求数据接口，返回值须包含total和data, eg: { data:[],total:100 }
 * @param options initPage,initPageSize
 * @returns { list, hasMore, loadMore, reset } list为加载的列表数组;hasmore为是否还有更多数据;loadMore为加载更多函数;reset为重置函数
 */
const useInfiniteScroll = (
  request: useInfiniteScrollRequest,
  options?: useInfiniteScrollOptions
): useInfiniteScrollReturn => {
  const { initPage = 1, initPageSize = 10 } = options || {}
  const [hasMore, setHasMore] = useState(true)
  const [list, setList] = useState([])

  const pager = useRef<{ pageNo: number; pageSize: number }>({
    pageNo: initPage,
    pageSize: initPageSize,
  })

  const loadMore = async () => {
    const { data = [], total = 0 } = await request(pager.current.pageNo, pager.current.pageSize)
    pager.current.pageNo = pager.current.pageNo + 1
    setHasMore(total > list.length + data?.length)
    if (data?.length) {
      setList((prev: any) => prev.concat(data))
    }
  }
  const reset = () => {
    setList([])
    setHasMore(true)
    pager.current.pageNo = 1
  }
  return { list, hasMore, loadMore, reset }
}

export default useInfiniteScroll
